<?php
/**
 * @description : the success callback page.
 * @author      : stephen.mo
 * @date        : 2010/09/10
 */
require_once "TVB/OAuth/common.inc.php";
#ini_set('display_errors','on');

$call_back         = (isset($_REQUEST['callback'])) ? $_REQUEST['callback'] : '#';
$pukey             = (isset($_REQUEST['pukey'])) ? $_REQUEST['pukey'] : NULL;
$lang              = (isset($_REQUEST['lang'])) ? $_REQUEST['lang'] : OAuthConfig::DEFAULT_SUPPORT_LANG;;
$order_ref         = (isset($_REQUEST['Ref'])) ? $_REQUEST['Ref'] : NULL;
$order_ref         = (empty($order_ref)) ? $_REQUEST['orderRef'] : $order_ref;

//setting page vars.
$base_server_path  = OAuthConfig::OAuthDomainUrl($_SERVER);
$plan_message_url  = $base_server_path.OAuthConfig::DEFAULT_SHOW_MESSAGE_URL;
$tmp_error_url     = NULL;

if (empty($call_back) || empty($pukey) || empty($order_ref)) {
    $tmp_error_url = OAuthUtils::genericError(array(1030));
}

//get some pkg info
$ptoken = OAuthUtils::getPToken();
$formData = OAuthUtils::getFormData($pukey,$ptoken);
if ($formData->retFlag!=1) {
    $tmp_error_url = OAuthUtils::genericError(array(1030));
}
if (!empty($tmp_error_url)) {
    OAuthUtils::redirectTo($tmp_error_url);
    exit;
}
if ($formData->retFlag==1) {
    $tmpData     = $formData->data;
    $pkg_id      = $tmpData->p_plan_id;
    $pkg_version = $tmpData->p_version_id;
    $reback_url  = (isset($tmpData->m_reback_url)) ? $tmpData->m_reback_url : '#';
    $p_lang      = (isset($tmpData->p_lang)) ? $tmpData->p_lang : NULL;
}

//get package information
if (!empty($pkg_id) && !empty($pkg_version)) {
    $pkgInfo = OAuthUtils::getPkgInfo($pkg_id,$pkg_version,$lang);
    $tmp_period = base64_encode($pkgInfo->title);
}

//successCallBack
//create a new member and get the member_id and update to order db.
$formVals['pukey']     = $pukey;
$formVals['ptoken']    = $ptoken;
$formVals['order_ref'] = $order_ref;
$formVals['referer']   = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : '';
$formVals['user_ip']   = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$formVals['lang']      = $lang;
$ret  = OAuthModel::getInstance()->successCallBack($formVals);
$flag = ($ret->retFlag==1) ? OAuthModelConfig::DEFAULT_CONST_SUCCESS : OAuthModelConfig::DEFAULT_CONST_FAILURE;

//redirect.
if ($ret->retFlag==1) {
    $redirect_to = $plan_message_url.'?call_back='.urlencode($call_back).'&reback_url='.urlencode($reback_url).'&act=pay&flag='.$flag.'&lang='.$lang.'&order_ref='.$order_ref.'&period='.$tmp_period;
}
else {
    $redirect_to = $plan_message_url.'?call_back='.urlencode($call_back).'&reback_url='.urlencode($reback_url).'&act=error&flag='.$flag.'&lang='.$lang.'&pukey='.$pukey.'&errids='.json_encode(array(1025,1026,1027));
}
OAuthUtils::redirectTo($redirect_to);
exit;
?>
